package com.bbzn.device.client.utils;

/**
 * @Author wulongbo
 * @Date 2021/12/25 15:36
 * @Version 1.0
 *  阻塞的有界队列
 */
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;


public class MapBlockingQueue<K, E> extends LinkedBlockingQueue {

    final ReentrantLock lock = new ReentrantLock();

    private final AbstractQueuedSynchronizer.ConditionObject notFull = (AbstractQueuedSynchronizer.ConditionObject) lock.newCondition();

    private final Map<K, E> map = Maps.newConcurrentMap();

    private int capacity;

    public MapBlockingQueue() {

    }

    public MapBlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public void put(K k, E e) throws InterruptedException {
        lock.lock();
        try {
            if (map.size() > capacity) {
                notFull.await();
            }
            map.put(k, e);
        } finally {
            lock.unlock();
        }
    }

    public E get(K k) {
        return map.get(k);
    }

}
